package com.hhuhh.smarthome.socket.udp;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioDatagramAcceptor;

import com.hhuhh.smarthome.socket.support.IoFilterHolder;

/**
 * @author John zhang
 * @version 0.1
 */
public class UdpServer {
	
	private NioDatagramAcceptor acceptor;
	private UdpClientIoHandler handler;

	public UdpServer() {}
	
	/**
	 * 构造一个简单的Udp客户端
	 * @return
	 */
	private NioDatagramAcceptor buildSimpleAcceptor() {
		NioDatagramAcceptor acceptor = new NioDatagramAcceptor ();

		acceptor.getSessionConfig ().setMinReadBufferSize ( 64 * 1024 );
		acceptor.getSessionConfig ().setMaxReadBufferSize ( 1024 * 1024 );
		acceptor.getSessionConfig ().setReadBufferSize ( 1024 * 1024 );
		acceptor.getSessionConfig ().setReceiveBufferSize ( 1024 * 1024 );
		
		// acceptor.getSessionConfig ().setIdleTime ( IdleStatus.BOTH_IDLE, 30 );

		acceptor.getFilterChain ().addLast ( "codec", new ProtocolCodecFilter ( IoFilterHolder.textLineCodecFactory () ) );
		acceptor.getFilterChain ().addLast ( "executor", IoFilterHolder.executorFilter ( 10 ) );
		acceptor.getFilterChain ().addLast ( "logger",IoFilterHolder.loggingFilter () );
		handler = new UdpClientIoHandler ();
		acceptor.setHandler ( handler );
		return acceptor;
	}
	
	public void startup() {
		this.acceptor = buildSimpleAcceptor();
		try {
			acceptor.bind( new InetSocketAddress("localhost", 1255) );
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main( String args[] ) {
		UdpServer server = new UdpServer();
		server.startup();
	}
	
}